package main

import (
	"ScreenRead/logic"
	"ScreenRead/logic/conf"
	"ScreenRead/util/img"
	"ScreenRead/util/log"
	"context"
	"github.com/disintegration/imaging"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"image"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// GetPort 获取 ws 端口
func (a *App) GetPort() int {
	return conf.Conf.Port
}

// GetLang 获取当前语言选项
func (a *App) GetLang() []string {
	return []string{
		conf.Conf.OCRLang,
		conf.Conf.WordsLang,
		conf.Conf.TransLang,
	}
}

// GetLangs 获取语言选项列表
func (a *App) GetLangs() []string {
	return conf.Conf.GetLangs()
}

// SetOCRLang 设置文字识别语言
func (a *App) SetOCRLang(lang string) bool {
	err := conf.Conf.SetOCRLang(lang)
	if err != nil {
		return false
	}

	return true
}

// SetWordsLang 设置原文语言
func (a *App) SetWordsLang(lang string) bool {
	err := conf.Conf.SetWordsLang(lang)
	if err != nil {
		return false
	}

	return true
}

// SetTransLang 设置译文语言
func (a *App) SetTransLang(lang string) bool {
	err := conf.Conf.SetTransLang(lang)
	if err != nil {
		return false
	}

	return true
}

// SetKey 设置 api 以及 secret 密钥
func (a *App) SetKey(apiKey, secretKey string) bool {
	err := conf.Conf.SetKey(apiKey, secretKey)
	if err != nil {
		return false
	}

	return true
}

// CustomTrans 自定义翻译
func (a *App) CustomTrans(words string) string {
	return logic.TextTrans(words)
}

// CustomShot 自定义框选截图
func (a *App) CustomShot(x0, y0, xt, yt int, base64Png string) {
	Arrays := &[2][]string{make([]string, 0), make([]string, 0)}
	defer runtime.EventsEmit(app.ctx, "ShotComplete", "", Arrays)

	if xt == 0 || yt == 0 {
		return
	}

	i, err := img.Base64PngToImg(base64Png)
	if err != nil {
		log.LogObj.Errorln(err)
		return
	}

	croppedPng := imaging.Crop(i, image.Rect(x0, y0, x0+xt, y0+yt))

	s, err := img.ImgToBase64Png(croppedPng)
	if err != nil {
		log.LogObj.Errorln(err)
		return
	}

	*Arrays = logic.ScreenRead(s)
}
